/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fr.istia.gesstages.actions;

import fr.istia.gesstages.metier.User;
import fr.istia.gesstages.util.Encryption;
import org.apache.struts2.dispatcher.SessionMap;

public class LoginAction extends ParentAction {

    private String login;
    private String password;

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    @Override
    public String execute() {
        return SUCCESS;
    }

    public String validateLogin() {
        try {
            if (metier.login(this.login, Encryption.md5(this.password))) {
                User user = metier.findUserByLogin(this.login);
                session.put("login", this.login);
                session.put("password", this.password);
                session.put("user",user);
                return SUCCESS;
            } else {
                addActionError(getText("login.error.password"));
                return INPUT;
            }
        } catch (Exception e) {
            addActionError(getText("login.error.user") + " : " + e.getMessage());
            return INPUT;
        }
    }

    public String disconnect() {
        if (session instanceof SessionMap) {
            try {
                ((SessionMap<String, Object>) session).invalidate();
                return SUCCESS;
            } catch (IllegalStateException e) {
                addActionError(getText("login.error.disconnect") + " : " + e.getMessage());
                return INPUT;
            }
        } else {
            addActionError(getText("login.error.disconnect.nosession"));
            return INPUT;
        }
    }
}
